package com.sky.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HuigeUtils;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.util.Locale;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    JwtProperties jwtProperties;

    @Autowired
    UserMapper userMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //创建HttpClient对象
        CloseableHttpClient aDefault = HttpClients.createDefault();
        //创建HttpGet请求对象
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HttpGet httpGet = new HttpGet( "https://api.weixin.qq.com/sns/jscode2session"+"?"
        +"js_code="+userLoginDTO.getCode()+"&"+"appid="+weChatProperties.getAppid()+"&"+"secret="+weChatProperties.getSecret()+"&grant_type=authorization_code");

        //发送请求获取响应对象

        UserLoginVO userLoginVO = new UserLoginVO();
        try {
            CloseableHttpResponse response = aDefault.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // 将JSON内容转为字符串
                String jsonString = EntityUtils.toString(entity, "UTF-8");

                // 使用Gson将JSON字符串转为Map
                Gson gson = new Gson();
                Type mapType = new TypeToken<Map<String, Object>>() {}.getType();
                Map<String, Object> resultMap = gson.fromJson(jsonString, mapType);

                String openid = (String) resultMap.get("openid");
                String phone = HuigeUtils.generate11DigitNumber();

                User user = new User();
                user.setOpenid(openid);
                user.setPhone(phone);
                user.setCreateTime(LocalDateTime.now());
                if (userMapper.count(openid)==null){
                    userMapper.saveuser(user);
                }
                Integer id = userMapper.getIdByOpenid(openid);


                resultMap.put(JwtClaimsConstant.USER_ID,id);

                String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(),
                        resultMap);


                UserLoginVO userLoginVO1 = new UserLoginVO();
                UserLoginVO build = userLoginVO1.builder().id(id.longValue()).openid(openid).token(token).build();

                response.close();
                userLoginVO = build;


            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

        return userLoginVO;
    }
}
